library(tidyverse)
library(readxl)
library(survival)
library(survminer)
library(ggsurvfit)

# %% Load data and processing ----
source("x28_help_funs.R")

path <- "D:/Work/TF/Ph1" # for working computer
data_file <- "XNW28012_SubjectList.xlsx"

# Load data
patient.info <- read_patient_info(path, data_file)

# PFS data processing ----
#   1. CurrentState为"治疗"时，删失在末次影像学日期（LastRadio）
#   2. CurrentState为终止时，继续查看EndReason：
##      2.1. Death：截至到EndDate（死亡日期）
##      2.2. PD：截至到LastRadio（进展日期, 即末次影像日期）
##      2.3. 其他：删失到LastRadio（末次影像日期）
#   3. 对于未进行肿评(BOR为空)的病人，删失到C1D1（首次影像日期）
pfs.info <- patient.info |>
  mutate(
    # 判断出现事件的情况，其他全为缺失。
    isEvent = if_else(
      EndReason == "PD" | EndReason == "Death",
      1,
      0,
      missing = 0
    ),
    # 末次计算日期
    EventDate = case_when(
      is.na(BOR) ~ C1D1, # 未进行肿评
      EndReason == "Death" ~ EndDate, # 死亡
      .default = LastRadio
    ) # 其他均是末次肿评时间
  )

pfs.info <- pfs.info |>
  mutate(
    Duration = as.numeric(difftime(EventDate + 1, C1D1, units = "days")) /
      30.4375
  ) |>
  select(
    Patient,
    Tumor,
    TF,
    Dose,
    BOR,
    EndReason,
    isDoseEsca,
    PriorLines,
    PriorIri,
    PriorIO,
    PtResistance,
    isEvent,
    Duration
  )


# %% Kepler-Meier analyse and plot function ----
plot_pfs2 <- function(data, tumor = "all", dose = "all", tf = "all") {
  tumor <- toupper(tumor)
  if (tumor != "ALL") {
    data <- data |>
      filter(Tumor == tumor)
  }

  dose <- toupper(dose)
  if (dose != "ALL") {
    data <- data |>
      filter(Dose == dose)
  }

  tf <- toupper(tf)
  if (tf == "POSITIVE" | tf == "POS") {
    data <- data |>
      filter(TF > 0)
  }
  if (tf == "NEGATIVE" | tf == "NEG") {
    data <- data |>
      filter(TF <= 0)
  }

  pfs.km <- survfit(Surv(time = data$Duration, event = data$isEvent) ~ 1)

  if (dose != "ALL") {
    title <- paste0(tumor, " (", dose, " mg/kg)")
  } else {
    title <- paste0(tumor, " (all)")
  }

  # Median PFS
  mpfs <- sprintf(
    "PFS: %0.2f [%0.2f, %0.2f]",
    surv_median(pfs.km)[2], # median PFS
    surv_median(pfs.km)[3],
    surv_median(pfs.km)[4] # 95% CI
  )

  pfs.fig <- ggsurvplot(
    pfs.km,
    data = data,
    # pval = TRUE, # p-value of log-rank test
    conf.int = TRUE,
    conf.int.style = "step",
    palette = "#2E9FDF", # The color of survival line
    linetype = 'strata',
    surv.median.line = "hv", # line for median PFS
    legend = "none", # remove legend
    break.time.by = 1, # break X axis in time intervals by one month
    risk.table = TRUE,
    risk.table.col = "strata",
    risk.table.height = 0.15,
    risk.table.y.text.col = TRUE,
    tables.theme = theme_cleantable(),
    ggtheme = theme_bw(),
    xlab = "PFS (months)",
    title = title,
    subtitle = mpfs
  )
  print(pfs.fig)

  pfs.km # Show PFS results in Console window
}


# %% Kepler-Meier analyse and plot function ----
plot_pfs <- function(pfs.set, title = "PFS Kepler-Meier plot") {
  data <- pfs.info |>
    filter(Patient %in% pfs.set$Patient)

  pfs.km <- survfit(
    Surv(time = data$Duration, event = data$isEvent) ~ 1,
    data = data
  )

  # Median PFS
  pfs.note <- sprintf(
    "PFS: %0.2f [%0.2f, %0.2f]",
    surv_median(pfs.km)[2], # median PFS
    surv_median(pfs.km)[3],
    surv_median(pfs.km)[4] # 95% CI
  )

  # Q??
  # 变量名使用data可以正确执行，不然就报错显示找不变量
  # 不知道错误是从哪里来的？
  pfs.fig <- ggsurvplot(
    pfs.km,
    data = data,
    # pval = TRUE, # p-value of log-rank test
    conf.int = TRUE,
    conf.int.style = "step",
    palette = "#2E9FDF", # The color of survival line
    linetype = 'strata',
    surv.median.line = "hv", # line for median PFS
    legend = "none", # remove legend
    break.time.by = 1, # break X axis in time intervals by one month
    risk.table = TRUE,
    risk.table.col = "strata",
    risk.table.height = 0.15,
    risk.table.y.text.col = TRUE,
    tables.theme = theme_cleantable(),
    ggtheme = theme_bw(),
    xlab = "PFS (months)",
    title = title,
    subtitle = pfs.note
  )
  print(pfs.fig)

  pfs.km # Show PFS results in Console window
}
